# -*- coding: gbk -*-
import os
import xml.dom.minidom

from utils import get_c_file_set


def update(context, fn):
    path = os.path.relpath(os.getcwd(), fn).removeprefix('..\\')
    DOMTree = xml.dom.minidom.parseString(context)
    for group in DOMTree.documentElement.getElementsByTagName('Group'):
        group_name = group.getElementsByTagName("GroupName")[0].childNodes[0].data
        if group_name.lower() in {'scns/src', 'drivers/scns/src'}:
            Files = group.getElementsByTagName("Files")[0]
            for file in Files.getElementsByTagName('File'):
                file.parentNode.removeChild(file)
            for name in get_c_file_set():
                # if not ((name.endswith('.c') or name.endswith('.h') or name.endswith('.md')) and os.path.exists(os.path.join('src', name))):
                if not ((name.endswith('.c')) and os.path.exists(os.path.join('src', name))):
                    continue
                File = DOMTree.createElement('File')
                FileName = DOMTree.createElement('FileName')
                FileName.appendChild(DOMTree.createTextNode(name))
                FileType = DOMTree.createElement('FileType')
                FileType.appendChild(DOMTree.createTextNode('1' if name.endswith('.c') else '5'))
                FilePath = DOMTree.createElement('FilePath')
                FilePath.appendChild(DOMTree.createTextNode(os.path.join(path, 'src', name)))
                File.appendChild(FileName)
                File.appendChild(FileType)
                File.appendChild(FilePath)
                Files.appendChild(File)
    return DOMTree.toxml()
